// 导入Promise
import {
	request , requestPayment
} from '../../request/index.js'


Page({
	data: {
		address: {},
		cart: [],
		totalPrice: 0,
		totalNum: 0
	},
	// 页面加载完毕
	onShow: function() {
		const address = wx.getStorageSync("address")
		let cart = wx.getStorageSync("cart") || []
		cart = cart.filter(item => item.checked)
		
		this.setData({address})
		this.setCart(cart)
	},
	
	// 封装底部栏计算
	setCart(cart){
		// const allChecked = cart.length ? cart.every(item => item.checked) : false;
		let totalPrice = 0
		let totalNum = 0
		cart.forEach(item => {
				totalPrice += item.num * item.goods_price
				totalNum += item.num
		})
		this.setData({
			cart,
			totalPrice,
			totalNum
		})
	},
	async payMent(){
		try{
			const token = wx.getStorageSync("token")
			// 没有token值
			if(!token){
				wx.navigateTo({
					url:"/pages/auth/index"
				})
				
				return;
			}
			// 有token
			// 请求头
			// const requestHeader = {Authorization : token}
			// 请求体
			
			// 订单总价格
			const order_price = this.data.totalPrice
			// 收货地址
			// 接口文档写必选，其实可传可不传
			const consignee_addr = this.data.address.all
			
			// 订单数组
			const cart = this.data.cart
			let goods = []
			cart.forEach(item => goods.push({
				goods_id:item.goods_id,
				goods_number:item.num,
				goods_price:item.goods_price
			}))	
			
			const requestBody = {order_price,goods}
			
			const res = await request({
				url:"/my/orders/create",
				data: requestBody,
				method:"POST",
			})
			// 解构 order_number 属性
			const {order_number} = res.data.message
			
			// 获取支付参数
			const payParams = await request({
				url:"/my/orders/req_unifiedorder",
				data:{order_number},
				method:"POST"
			})
			// 解构 pay 属性
			const  {pay} = payParams.data.message
			// 发起微信支付，企业账户有
			await requestPayment(pay)
			// 查询支付状态
			const queryPaymentStatus = await request({
				url:"/my/orders/chkOrder",
				data: {order_number},
				method:"POST",
			})
			
			await wx.showToast({
				title:"支付成功"
			})
			
			
			let newCart = wx.getStorageSync("cart")
			newCart = newCart.filter(item => !item.checked)
			wx.setStorageSync("cart",newCart)
			
			// 支付成功后跳转到订单页面
			wx.navigateTo({
				url:"pages/order/index"
			})
			
			
			
		}catch(e){
			await wx.showToast({
				title:"支付失败",
				icon:"error"
			})
			
			console.log(e);
		}
	}
	
	
	
})

